//
//  SwitchPageView.m
//  RongRTCMeeting
//
//  Created by LiuLinhong on 2017/08/25.
//  Copyright © 2017年 Beijing Rongcloud Network Technology Co. , Ltd. All rights reserved.
//

#import "SwitchPageViewControl.h"
#import "MeetingViewController.h"
#import "SwitchPageViewCell.h"
#import <RongRTCLib/RongRTCEngine.h>
#import "AppDelegate.h"

@interface SwitchPageViewControl ()

@property (nonatomic, strong) MeetingViewController *meetingViewController;
@property (nonatomic, assign) NSInteger pageIndex;
@property (nonatomic, assign) CGFloat cellX;

@end


@implementation SwitchPageViewControl


- (instancetype _Nonnull )initWithViewBuilder:(NSViewController *)vc;
{
    self = [super init];
    
    if (self)
    {
        self.meetingViewController = (MeetingViewController *)vc;
        self.pageIndex = 0;
        self.meetingViewController = (MeetingViewController *) vc;
        self.remoteVideoCellArray = [NSMutableArray array];
        self.cellX = 24;
    }
    return self;
}

- (void)reloadCellInPageView
{
    [self.remoteVideoCellArray enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        dispatch_async(dispatch_get_main_queue(), ^{
            NSView *view = (NSView *)obj;
            [view removeFromSuperview];
        });
    }];
    
    [self initSwitchPageView:self.pageIndex];
}

- (void)initSwitchPageView:(NSInteger)pageIndex
{
    [self.remoteVideoCellArray removeAllObjects];
    NSInteger cellCountInPage = [self.dataSource switchPageViewControl:self numberOfCellsInSwitchPageView:pageIndex];
    self.cellX = 24;
    for (NSInteger i = 0; i < cellCountInPage; i++)
    {
        NSIndexPath *indexPath = [NSIndexPath indexPathForItem:i inSection:pageIndex];
        [self addCellOnBottomView:indexPath];
        
        NSDictionary *dic = [self.dataSource switchPageViewControl:self cellViewForIndex:indexPath];
        [self loadCellVideoView:indexPath withUserID:dic[kUserID]];
    }
}

- (void)loadCellVideoView:(NSIndexPath *)indexPath withUserID:(NSString *)userID
{
    NSDictionary *dic = [self.dataSource switchPageViewControl:self cellViewForIndex:indexPath];
    NSView *view = (NSView *)dic[kRemoteVideoView];
    SwitchPageViewCell *cell;
    for (SwitchPageViewCell *tmpCell in self.remoteVideoCellArray)
    {
        if ([tmpCell.userID isEqualToString:userID])
        {
            tmpCell.videoView = view;
            cell = tmpCell;
        }
    }
    
    NSInteger pIndex = indexPath.section;
    NSInteger cIndex = indexPath.item;
    [cell stopLoadingAnimation];
    
    if (pIndex == LarkMeetingManager.selectedSwitchPageIndex && cIndex == LarkMeetingManager.selectedSwitchCellIndex && LarkMeetingManager.isSwitchVideoView)
    {
        cell.frame = CGRectMake(cell.frame.origin.x, cell.frame.origin.y, self.meetingViewController.localVideoViewModel.cellVideoView.frame.size.width, self.meetingViewController.localVideoViewModel.cellVideoView.frame.size.height);
        [cell addSubview:self.meetingViewController.localVideoViewModel.cellVideoView];
        
        AppDelegate *appDelegate = (AppDelegate *)[NSApplication sharedApplication].delegate;
        [appDelegate.childWindow.contentView addSubview:view];
    }
    else
        [cell addSubview:view];
    
    NSInteger avType = [dic[kAudioVideoType] integerValue];
    if (avType != RongRTC_User_Only_Audio && avType != RongRTC_User_Audio_Video_None)
        [cell.switchHeadIconView removeFromSuperview];
}

- (void)addCellOnBottomView:(NSIndexPath *)indexPath
{
    NSEdgeInsets tmpInset = [self.delegate switchPageViewControl:self insetOfCellAtIndex:indexPath];
    NSDictionary *dic = [self.dataSource switchPageViewControl:self cellViewForIndex:indexPath];
//    NSView *view = (NSView *)dic[@"remoteVideoView"];
//    SwitchPageViewCell *cell = [[SwitchPageViewCell alloc] initWithFrame:CGRectMake(self.cellX, 0, view.frame.size.width, view.frame.size.height) withSwitchPage:self];
    SwitchPageViewCell *cell = [[SwitchPageViewCell alloc] initWithFrame:CGRectMake(self.cellX, 0, kCellSize, kCellSize) withSwitchPage:self];
    cell.userID = dic[kUserID];
    cell.indexPath = indexPath;
//    cell.videoView = view;
    
    cell.switchHeadIconView = (HeadIconView *)dic[kSwitchHeadIcon];
    [cell addSubview:cell.switchHeadIconView];
    NSInteger pIndex = indexPath.section;
    NSInteger cIndex = indexPath.item;
    
    if (pIndex == LarkMeetingManager.selectedSwitchPageIndex && cIndex == LarkMeetingManager.selectedSwitchCellIndex && LarkMeetingManager.isSwitchVideoView)
    {
        cell.frame = CGRectMake(cell.frame.origin.x, cell.frame.origin.y, self.meetingViewController.localVideoViewModel.cellVideoView.frame.size.width, self.meetingViewController.localVideoViewModel.cellVideoView.frame.size.height);
        [cell addSubview:self.meetingViewController.localVideoViewModel.cellVideoView];
        
//        AppDelegate *appDelegate = (AppDelegate *)[NSApplication sharedApplication].delegate;
//        [appDelegate.childWindow.contentView addSubview:view];
    }
//    else
//        [cell addSubview:view];
    
    [self.meetingViewController.meetingViewBuilder.videosBottomView addSubview:cell];
    [cell startLoadingAnimation];
    DLog(@"LLH...... cell.frame: %@", NSStringFromRect(cell.frame));
    
    //////////////////////////////////////
    /*
    CGRect wRect = self.meetingViewController.view.window.frame;
//    CGRect cRect = self.meetingViewController.view.window.contentView.frame;
    CGRect rect = CGRectMake(wRect.origin.x + self.cellX, wRect.origin.y, cell.frame.size.width, cell.frame.size.height);
//    NSWindow *childCellWindow = [[NSWindow alloc] initWithContentRect:rect styleMask:NSClosableWindowMask backing:NSBackingStoreBuffered defer:NO];
//    childCellWindow.backgroundColor = [NSColor blueColor];
//    [childCellWindow setOpaque:NO];
//    [self.meetingViewController.view.window addChildWindow:childCellWindow ordered:NSWindowAbove];
    ///////////////////////////////
    
    NSWindow *cellWindow;
    cellWindow = (NSWindow *)self.windowDic[userID];
    if (!cellWindow)
    {
        cellWindow = [[NSWindow alloc] initWithContentRect:rect styleMask:NSClosableWindowMask backing:NSBackingStoreBuffered defer:NO];
        [self.windowDic setObject:cellWindow forKey:userID];
    }
    
    cellWindow.backgroundColor = [NSColor purpleColor];
    [cellWindow setOpaque:NO];
    [self.meetingViewController.view.window addChildWindow:cellWindow ordered:NSWindowAbove];
    
    [self.remoteWindowArray addObject:cellWindow];
     */
    //////////////////////////////
    
    CGFloat cellIntervalX = cell.frame.size.width + tmpInset.right;
    self.cellX += cellIntervalX;
    [self.remoteVideoCellArray addObject:cell];
    
    self.cellNumberInFullPage = self.meetingViewController.meetingViewBuilder.videosBottomView.frame.size.width / cellIntervalX;
}

- (void)addNewCellView:(NSIndexPath *)indexPath;
{
    if (indexPath.section != self.pageIndex)
    {
        DLog(@"LLH...... addNewCellView pageIndex: %zd Return!!!", self.pageIndex);
        return;
    }
    
    DLog(@"LLH...... addNewCellView pageIndex: %zd", self.pageIndex);
    [self addCellOnBottomView:indexPath];
}

- (void)removeCellView:(NSIndexPath *)indexPath
{
    if (indexPath.section > self.pageIndex)
    {
        DLog(@"LLH...... removeCellView Page: %zd Return!!!", indexPath.section);
        return;
    }
    else if (indexPath.section < self.pageIndex)
    {
        NSInteger tmpCellCountInPage = [self.dataSource switchPageViewControl:self numberOfCellsInSwitchPageView:self.pageIndex];
        if (tmpCellCountInPage == 0)
        {
            if (LarkMeetingManager.isSwitchVideoView && LarkMeetingManager.selectedSwitchPageIndex == self.pageIndex)
            {
                if (LarkMeetingManager.selectedSwitchCellIndex == 0)
                {
                    LarkMeetingManager.selectedSwitchPageIndex--;
                    LarkMeetingManager.selectedSwitchCellIndex = self.cellNumberInFullPage - 1;
                }
                else
                    LarkMeetingManager.selectedSwitchCellIndex--;
            }
            
            [self moveLeftSwitchPage];
        }
        else if (LarkMeetingManager.selectedSwitchPageIndex == self.pageIndex)
        {
            [self.remoteVideoCellArray enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
                NSView *view = (NSView *)obj;
                [view removeFromSuperview];
            }];
            
            LarkMeetingManager.selectedSwitchCellIndex--;
            [self.remoteVideoCellArray removeObjectAtIndex:0];
            self.cellX = 24;
            NSInteger cellCountInPage = [self.dataSource switchPageViewControl:self numberOfCellsInSwitchPageView:self.pageIndex];
            for (NSInteger i = 0; i < cellCountInPage; i++)
            {
                NSIndexPath *indexPath = [NSIndexPath indexPathForItem:i inSection:self.pageIndex];
                NSEdgeInsets tmpInset = [self.delegate switchPageViewControl:self insetOfCellAtIndex:indexPath];
                SwitchPageViewCell *cell = (SwitchPageViewCell *)self.remoteVideoCellArray[i];
                cell.indexPath = indexPath;
                cell.frame = CGRectMake(self.cellX, cell.frame.origin.y, cell.frame.size.width, cell.frame.size.height);
                [self.meetingViewController.meetingViewBuilder.videosBottomView addSubview:cell];
                DLog(@"LLH...... cell.frame: %@", NSStringFromRect(cell.frame));
                self.cellX += cell.frame.size.width + tmpInset.right;
            }
        }
        else
            [self reloadCellInPageView];
    }
    else if (indexPath.section == self.pageIndex)
    {
        NSInteger cellCountInPage = [self.dataSource switchPageViewControl:self numberOfCellsInSwitchPageView:self.pageIndex];
        if (LarkMeetingManager.isSwitchVideoView)
        {
            if (cellCountInPage == 0)
                [self moveLeftSwitchPage];
            else if (LarkMeetingManager.selectedSwitchCellIndex == indexPath.item || cellCountInPage == self.cellNumberInFullPage)
                [self reloadCellInPageView];
            else
            {
                [self.remoteVideoCellArray enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
                    NSView *view = (NSView *)obj;
                    [view removeFromSuperview];
                }];
                
                LarkMeetingManager.selectedSwitchCellIndex--;
                [self.remoteVideoCellArray removeObjectAtIndex:indexPath.item];
                self.cellX = 24;
                for (NSInteger i = 0; i < cellCountInPage; i++)
                {
                    NSIndexPath *indexPath = [NSIndexPath indexPathForItem:i inSection:self.pageIndex];
                    NSEdgeInsets tmpInset = [self.delegate switchPageViewControl:self insetOfCellAtIndex:indexPath];
                    SwitchPageViewCell *cell = (SwitchPageViewCell *)self.remoteVideoCellArray[i];
                    cell.indexPath = indexPath;
                    cell.frame = CGRectMake(self.cellX, cell.frame.origin.y, cell.frame.size.width, cell.frame.size.height);
                    [self.meetingViewController.meetingViewBuilder.videosBottomView addSubview:cell];
                    DLog(@"LLH...... cell.frame: %@", NSStringFromRect(cell.frame));
                    self.cellX += cell.frame.size.width + tmpInset.right;
                }
            }
        }
        else
        {
            DLog(@"LLH...... removeCellView pageIndex: %zd", self.pageIndex);
            if (cellCountInPage == 0 && self.pageIndex > 0)
                [self moveLeftSwitchPage];
            else
                [self reloadCellInPageView];
        }
    }
}

- (void)moveLeftSwitchPage
{
    if (self.pageIndex == 0)
    {
        DLog(@"LLH...... moveLeftSwitchPage 到头儿了 Return");
        return;
    }
    
    self.pageIndex--;
    [self reloadCellInPageView];
}

- (void)moveRightSwitchPage
{
    NSInteger totalPage = [self.dataSource numberOfPagesInSwitchPageViewControl:self];
    
    if (totalPage == self.pageIndex + 1 || totalPage == 0)
    {
        DLog(@"LLH...... moveRightSwitchPage 到尾了 Return");
        return;
    }
    
    self.pageIndex++;
    [self reloadCellInPageView];
}

- (void)switchPageCellPressed:(NSIndexPath *_Nonnull)indexPath
{
    [self.delegate switchPageViewControl:self didSelectedCellAtIndexPath:indexPath];
}

@end

